import json

from channels.generic.websocket import AsyncJsonWebsocketConsumer
from . import data_grad
from concurrent.futures import ThreadPoolExecutor, as_completed, wait, FIRST_COMPLETED, ALL_COMPLETED
import time


class TableConsumer(AsyncJsonWebsocketConsumer):
    user_cnt = 0
    table = None

    async def connect(self):
        TableConsumer.user_cnt += 1
        self._id = TableConsumer.user_cnt
        self.table = 'table_{}'.format(self.scope['url_route']['kwargs']['table_id'])
        # Join room group
        await self.channel_layer.group_add(self.table, self.channel_name)
        await self.accept()
        await self.send(text_data=json.dumps({
            'message': "hello？{}:{}:{}".format(self.table, self.channel_name, str(TableConsumer.user_cnt))
        }))
        print("start")

    async def disconnect(self, close_code):
        TableConsumer.user_cnt -= 1
        TableConsumer._loop = False
        # Leave room group
        await self.channel_layer.group_discard(self.table, self.channel_name)
        await self.channel_layer.group_send(self.table, {'type': 'message', 'message': "user {} leave".format(
            str(TableConsumer.user_cnt))})

    # Receive message from WebSocket
    async def receive_json(self, content, **kwargs):
        # Send message to room group
        await self.channel_layer.group_send(self.table, {'type': 'message', 'message': content})

    # Receive message from room group
    async def message(self, event):
        try:
            message = event['message']
        except Exception as e:
            message = None
            print("message was not transmitted.")
        else:
            if message == "get-info":
                mem_tot, mem_percent, mem_use, mem_available = data_grad.get_meminfo()
                (logical_cpu, real_cpu), cpu_percent = data_grad.get_cpuinfo()
                await self.send(text_data=json.dumps({
                    'message': message,
                    "logical_cpu": logical_cpu,
                    "real_cpu": real_cpu,
                    "cpu_percent": cpu_percent,
                    "mem_tot": mem_tot,
                    "mem_percent": mem_percent,
                    "mem_use": mem_use,
                    "mem_available": mem_available
                }))
            else:
                print("other message.")
                await self.send(text_data=json.dumps({
                    'message': message,
                }))
            # Send message to WebSocket
            # await self.send_json(message)

    def __del__(self):
        TableConsumer._loop = False
